package com.goodfather.textbook.youdao.pad.util;

import android.os.Parcelable;
import android.text.TextUtils;

import com.google.gson.Gson;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zerup on 17/4/24.
 */

public class StringUtil {
    public static String printParcel(Parcelable parcelable) {
        String json = new Gson().toJson(parcelable);
        return json;
    }

    public static String[] listToArray(ArrayList<String> list) {
        if (list == null) {
            return new String[0];
        }
        String[] array = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i);
        }
        return array;
    }

    //移除string前后的双引号
    public static String getStringWithoutQuote(String s) {
        if (s == null) {
            return null;
        }
        s = s.replaceFirst("\"", "");
        if (TextUtils.isEmpty(s)) {
            return "";
        }
        if (s.endsWith("\"")) {
            s = s.substring(0, s.length() - 1);
        }
        return s;
    }

    /**
     * 验证邮箱输入是否合法
     *
     * @param email
     * @return
     */
    public static boolean isValidEmail(String email) {
        String emailPattern = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,8}";
        boolean result = Pattern.matches(emailPattern, email);
        return result;
    }

    public static String getMaskedEmail(String email) {
        if (!isValidEmail(email)) {
            return email;
        }
        int idx = email.indexOf('@');
        String s1 = email.substring(0, idx);
        String s2 = email.substring(idx, email.length());
        String rst = "";
        rst += s1.substring(0, 1);
        rst += "****";
        rst += s1.substring(s1.length() - 1, s1.length());
        rst += ("@" + s2);
        return rst;
    }


    public static boolean isValidPhone(String phone){
        String REGEX_MOBILE_EXACT  = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(16[6])|(17[0,1,3,5-8])|(18[0-9])|(19[8,9]))\\d{8}$";
        boolean result = Pattern.matches(REGEX_MOBILE_EXACT,phone);
        return result;
    }

    /**
     * @param s
     * @return 判断字符串是否由0-9组成
     */
    public static boolean isAllNumber(String s) {
        if (TextUtils.isEmpty(s)) {
            return false;
        }
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                continue;
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断字符串是否由0-9和字母组成
     *
     * @param s
     * @return
     */
    public static boolean isNumberOrLetter(String s) {
        if (TextUtils.isEmpty(s)) {
            return false;
        }
        String pattern = "^[A-Za-z0-9]+$";
        boolean result = Pattern.matches(pattern, s);
        return result;
    }

    public static InputStream str2Stream(String str) {
        if (str == null) {
            return null;
        }
        InputStream inputStream = null;
        try {
            inputStream = new ByteArrayInputStream(str.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * This is a string replacement method.
     */
    public final static String replaceString(String source, String oldStr,
                                             String newStr) {
        StringBuilder sb = new StringBuilder(source.length());
        int sind = 0;
        int cind = 0;
        while ((cind = source.indexOf(oldStr, sind)) != -1) {
            sb.append(source.substring(sind, cind));
            sb.append(newStr);
            sind = cind + oldStr.length();
        }
        sb.append(source.substring(sind));
        return sb.toString();
    }

    /**
     * Replace string
     */
    public final static String replaceString(String source, Object[] args) {
        int startIndex = 0;
        int openIndex = source.indexOf('{', startIndex);
        if (openIndex == -1) {
            return source;
        }

        int closeIndex = source.indexOf('}', startIndex);
        if ((closeIndex == -1) || (openIndex > closeIndex)) {
            return source;
        }

        StringBuilder sb = new StringBuilder();
        sb.append(source.substring(startIndex, openIndex));
        while (true) {
            String intStr = source.substring(openIndex + 1, closeIndex);
            int index = Integer.parseInt(intStr);
            sb.append(args[index]);

            startIndex = closeIndex + 1;
            openIndex = source.indexOf('{', startIndex);
            if (openIndex == -1) {
                sb.append(source.substring(startIndex));
                break;
            }

            closeIndex = source.indexOf('}', startIndex);
            if ((closeIndex == -1) || (openIndex > closeIndex)) {
                sb.append(source.substring(startIndex));
                break;
            }
            sb.append(source.substring(startIndex, openIndex));
        }
        return sb.toString();
    }

    /**
     * Replace string.
     */
    public final static String replaceString(String source,
                                             Map<String, Object> args) {
        int startIndex = 0;
        int openIndex = source.indexOf('{', startIndex);
        if (openIndex == -1) {
            return source;
        }

        int closeIndex = source.indexOf('}', startIndex);
        if ((closeIndex == -1) || (openIndex > closeIndex)) {
            return source;
        }

        StringBuilder sb = new StringBuilder();
        sb.append(source.substring(startIndex, openIndex));
        while (true) {
            String key = source.substring(openIndex + 1, closeIndex);
            Object val = args.get(key);
            if (val != null) {
                sb.append(val);
            }

            startIndex = closeIndex + 1;
            openIndex = source.indexOf('{', startIndex);
            if (openIndex == -1) {
                sb.append(source.substring(startIndex));
                break;
            }

            closeIndex = source.indexOf('}', startIndex);
            if ((closeIndex == -1) || (openIndex > closeIndex)) {
                sb.append(source.substring(startIndex));
                break;
            }
            sb.append(source.substring(startIndex, openIndex));
        }
        return sb.toString();
    }

    /**
     * This method is used to insert HTML block dynamically
     *
     * @param source        the HTML code to be processes
     * @param bReplaceNl    if true '\n' will be replaced by <br>
     * @param bReplaceTag   if true '<' will be replaced by < and
     *                      '>' will be replaced by >
     * @param bReplaceQuote if true '\"' will be replaced by "
     */
    public final static String formatHtml(String source, boolean bReplaceNl,
                                          boolean bReplaceTag, boolean bReplaceQuote) {

        StringBuilder sb = new StringBuilder();
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char c = source.charAt(i);
            switch (c) {
                case '\"':
                    if (bReplaceQuote)
                        sb.append("");
                    else
                        sb.append(c);
                    break;

                case '<':
                    if (bReplaceTag)
                        sb.append("<");
                    else
                        sb.append(c);
                    break;

                case '>':
                    if (bReplaceTag)
                        sb.append(">");
                    else
                        sb.append(c);
                    break;

                case '\n':
                    if (bReplaceNl) {
                        if (bReplaceTag)
                            sb.append("<br>");
                        else
                            sb.append("<br>");
                    } else {
                        sb.append(c);
                    }
                    break;

                case '\r':
                    break;

                case '&':
                    sb.append("&");
                    break;

                default:
                    sb.append(c);
                    break;
            }
        }
        return sb.toString();
    }

    /**
     * Pad string object
     */
    public final static String pad(String src, char padChar, boolean rightPad,
                                   int totalLength) {

        int srcLength = src.length();
        if (srcLength >= totalLength) {
            return src;
        }

        int padLength = totalLength - srcLength;
        StringBuilder sb = new StringBuilder(padLength);
        for (int i = 0; i < padLength; ++i) {
            sb.append(padChar);
        }

        if (rightPad) {
            return src + sb.toString();
        } else {
            return sb.toString() + src;
        }
    }

    /**
     * Get hex string from byte array
     */
    public final static String toHexString(byte[] res) {
        StringBuilder sb = new StringBuilder(res.length << 1);
        for (final byte re : res) {
            String digit = Integer.toHexString(0xFF & re);
            if (digit.length() == 1) {
                digit = '0' + digit;
            }
            sb.append(digit);
        }
        return sb.toString().toUpperCase();
    }

    /**
     * Get byte array from hex string
     */
    public final static String[] toStringArray(String hexString) {
        String[] codeString = hexString.split(",");
        return codeString;
    }

    /**
     * 将数字转换成大写
     *
     * @param str
     * @return
     */
    public static String getChinese(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            switch (c) {
                case '0':
                    sb.append("零");
                    break;
                case '1':
                    sb.append("一");
                    break;
                case '2':
                    sb.append("二");
                    break;
                case '3':
                    sb.append("三");
                    break;
                case '4':
                    sb.append("四");
                    break;
                case '5':
                    sb.append("五");
                    break;
                case '6':
                    sb.append("六");
                    break;
                case '7':
                    sb.append("七");
                    break;
                case '8':
                    sb.append("八");
                    break;
                case '9':
                    sb.append("九");
                    break;
                default:
                    break;
            }
        }
        return sb.toString();
    }

    //获取string中字符c出现次数
    public static int getCharCount(String s, char c) {
        int count = 0;
        int i = s.indexOf(c);
        if (i != -1) {
            while (i < s.length()) {
                if (s.charAt(i) == c)
                    count++;
                i++;
            }
        }
        return count;
    }

    public static boolean isEmpty(CharSequence s) {
        return s == null || s.equals("");
    }


    public static String getMD5(String info) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("UTF-8"));
            byte[] encryption = md5.digest();

            StringBuilder strBuf = new StringBuilder();
            for (final byte anEncryption : encryption) {
                if (Integer.toHexString(0xff & anEncryption).length() == 1) {
                    strBuf.append("0").append(Integer.toHexString(0xff & anEncryption));
                } else {
                    strBuf.append(Integer.toHexString(0xff & anEncryption));
                }
            }
            return strBuf.toString();
        } catch (NoSuchAlgorithmException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

//    public static Bundle getBundleFromJsonStr(String params) {
//        Bundle bundle = new Bundle();
//        HashMap<String, String> args = GsonUtil.gson.fromJson(params, HashMap.class);
//        try {
//            for (String key : args.keySet()) {
//                bundle.putString(key, args.get(key));
//            }
//        } catch (Throwable e) {
//            L.e("",e.getMessage());
//        }
//        return bundle;
//    }

    public static int castToInt(String target, int defaultValue) {
        int value;
        try {
            value = Integer.valueOf(target);
        } catch (Exception e) {
            return defaultValue;
        }
        return value;
    }

    public static long string2Long(String s) {
        int result = 0;
        if (!isEmpty(s)) {
            try {
                result = Integer.valueOf(s);
            } catch (Exception e) {
                L.d("string2Int Exception" + e.toString());
            }
        }
        return result;
    }

    //example 1分2秒
    public static String formatTimeMS(long sec) {
        String result = "0\"";
        if (sec != 0) {
            result = String.valueOf((int) Math.floor(sec / 60.0)) + "分" + String.valueOf(sec % 60) + "秒";
        }
        return result;
    }

    public static boolean firstCharIsLetter(String s) {
        if (isEmpty(s)) return true;
        char c = s.charAt(0);
        int i = (int) c;
        return ((i >= 65 && i <= 90) || (i >= 97 && i <= 122));

    }

    /**
     * 验证身份证
     */
    public static boolean isIdCard(String id) {
        if (isAllNumber(id) && id.length() == 15) {
            return true;
        }
        if (isAllNumber(id) && id.length() == 18) {
            return true;
        }
        return id != null && id.length() == 18 && isAllNumber(id.substring(0, 17)) &&
                (id.charAt(17) == 'X' || id.charAt(17) == 'x');
    }
    public static boolean isNetUrl(String str) {
        return !isEmpty(str) && (str.startsWith("http://") || str.startsWith("https://"));
    }

    /**
     * 判断字符串中是否包含中文
     *
     * @param str
     * @return
     */
    public static boolean isContainChinese(String str) {

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        return m.find();
    }

    /**
     * url编码（中文编码，空格编码）
     * @param url
     * @return
     */
    public static String URLEncode(String url){

        if (isContainChinese(url)){
            try {
                String encodeUrl = URLEncoder.encode(url, "UTF-8");
                encodeUrl = encodeUrl.replace("%3A", ":");
                encodeUrl = encodeUrl.replace("%2F", "/");
                encodeUrl = encodeUrl.replace("+", "%20");
                return encodeUrl;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return url;
            }

        }else {
            return url.replace(" ", "%20");
        }
    }

    /**
     * 去掉字符串中的中文
     *
     * @param str
     * @return
     */
    public static String removeChinese(String str) {
        Pattern pat = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher mat = pat.matcher(str);
        return mat.replaceAll("");
    }

    /**
     * 去掉字符串中的特殊字符(保留原句子中的“,”和“.”)
     */
    public static String removeSpecialCharacters(String str) {
        // 清除掉所有特殊字符
        String regEx="[`~!@#$%^&*()+=|{}:;\\[\\]<>/?！￥…（）—【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }


    /**
     * 全角转半角
     *
     * @param input String.
     * @return 半角字符串
     */
    public static String ToDBC(String input) {
        if (input == null) {
            return "";
        }
        char c[] = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == '\u3000') {
                c[i] = ' ';
            } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
                c[i] = (char) (c[i] - 65248);

            }
        }
        return new String(c);
    }


    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    public static String removeBOM(String data) {
        if (TextUtils.isEmpty(data)) {
            return data;
        }

        if (data.startsWith("\ufeff")) {
            return data.substring(1);
        } else {
            return data;
        }
    }

    /**
     * 数字转中文
     * @param string
     * @return
     */
    public static String toChinese(String string) {
        String[] s1 = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
        String[] s2 = { "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };

        String result = "";

        int n = string.length();
        for (int i = 0; i < n; i++) {
            int num = string.charAt(i) - '0';
            if (i != n - 1 && num != 0) {
                result += s1[num] + s2[n - 2 - i];
            } else {
                result += s1[num];
            }
        }
        return result;
    }
}
